package net.zjitc.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Random;

public class MD5WithSaltUtil {

    // 生成随机盐值
    public static String generateSalt(int length) {
        Random random = new Random();
        byte[] salt = new byte[length];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 将密码和盐值组合后进行 MD5 哈希
    public static String hashPasswordWithSalt(String password, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(salt.getBytes());
            byte[] hashedPassword = md.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(hashedPassword);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    // 验证密码
    public static boolean verifyPassword(String password, String salt, String storedHash) {
        String hashToVerify = hashPasswordWithSalt(password, salt);
        return hashToVerify.equals(storedHash);
    }

    public static void main(String[] args) {
        String password = "mySecurePassword";
        String salt = generateSalt(16); // 生成 16 字节的盐值
        String hashedPassword = hashPasswordWithSalt(password, salt);

        System.out.println("Salt: " + salt);
        System.out.println("Hashed Password: " + hashedPassword);

        // 验证密码
        boolean isMatch = verifyPassword("mySecurePassword", salt, hashedPassword);
        System.out.println("Password match: " + isMatch);
    }
}
